import { _decorator, CCInteger, CCString, Component, Node } from 'cc';
import { EventName } from '../../Enum/Enum';
const { ccclass, property } = _decorator;

/**
 * 节点长按监听组件 触发不了，找不到原因，弃用
 * @deprecated
 */
@ccclass('BtnLongPress')
export class BtnLongPress extends Component {
    @property({ type: Node, tooltip: '需要触发长按监听的目标节点,\\n如果active为false则不提交触发事件', displayName: '目标节点' })
    public target_node: Node[] = [];// 目标节点 
    @property({ type: CCInteger, tooltip: '长按触发长按的时长', displayName: '触发长按的时长(ms)' })
    public btn_hover_time: number = 1500;// hover的时长,监听长按触发长按的总时间
    @property({ tooltip: '长按触发的节点，要提交的事件名称 node.emit(event_name)', displayName: '触发节点事件名' })
    public event_name: string = EventName.Long_press;// 触发长按的按钮名称

    private _press_node_temp: Map<Node, number> = new Map();// 存储长按的节点

    start() {
        this.target_node.forEach((node: Node) => {
            this.bind_touch_event(node)
        })
    }
    /**
     * 长按组件入口函数
     * 在此节点添加长按监听,触发后会提交长按事件 node.emit(this.event_name);
     * <br/>如果node.active == false则不会触发长按事件，直到为true
     * @param node 
     */
    bind_touch_event(node: Node) {
        console.log(node.name, '绑定长按事件');
        node.on(Node.EventType.TOUCH_START, this.onTouchStart(node), this);
        node.on(Node.EventType.TOUCH_END, this.onTouchEnd(node), this);
    }

    onTouchEnd(node: Node): Function {
        console.log(node.name, '长按结束');
        this._press_node_temp.delete(node);
        return;
    }
    onTouchStart(node: Node): Function {
        console.log(node.name, '长按开始');
        this._press_node_temp.set(node, new Date().getTime());
        return;
    }

    update(deltaTime: number) {
        this.trigger()

    }
    trigger() {
        if (this._press_node_temp.size > 0) {
            const time2 = new Date().getTime()
            for (let [node, time] of this._press_node_temp.entries()) {
                if (node.active == false) {
                    this.onTouchEnd(node)
                    continue
                }
                if (time2 - time > this.btn_hover_time) {
                    time = time2
                    node.emit(this.event_name);
                }
            }
        }

    }


}

